<!--
 * @description:
 * @author: cuicui
 * @Date: 2023-11-23 21:08:50
 * @LastEditTime: 2023-12-02 09:26:54
 * @LastEditors: cuicui
-->
<template>
  <business-layout title='用户列表'>
    <div class='table-page-search-wrapper' slot='query'>
      <a-row style='height: 40px;'>
        <a-form style='height: 40px;' :form='form' layout='inline' @submit='handleQueryData'>
          <a-col :span='4' style='height: 40px;'>
            <a-form-item>
              <a-input v-decorator="['name']" allowClear placeholder='请输入账号' />
            </a-form-item>
          </a-col>
          <a-col :span='4' style='height: 40px;margin-left: 10px'>
            <a-form-item>
              <a-input v-decorator="['phone']" allowClear placeholder='请输入手机号' />
            </a-form-item>
          </a-col>
          <a-col :span='6' style='height: 40px;margin-left: 10px'>
            <a-form-item>
              <a-button type='primary' html-type='submit'>
                <a-icon type='search' />
                查询
              </a-button>
              <a-button html-type='reset' style='margin-left: 10px;' @click='handleResetData'>
                重置
              </a-button>
            </a-form-item>
          </a-col>
        </a-form>
      </a-row>
    </div>

    <template slot='btns'>
      <a-button type='primary' icon='plus' @click='handleAdd'>新建</a-button>
    </template>
    <s-table
      ref='table'
      size='default'
      rowKey='id'
      :columns='columns'
      :data='loadData'
      :show-pagination='true'
    >
      <span slot='serial' slot-scope='text, record, index'>
        {{ index + 1 }}
      </span>
      <span slot='gender' slot-scope='text, record, index'>
        {{ text === 'F' ? '女' : '男' }}
      </span>
      <span slot='enabled' slot-scope='text'>
         <a-tag :color=' text | statusTypeFilter'> {{ text | statusFilter }} </a-tag>
      </span>
      <span slot='userType' slot-scope='text'>
         <a-tag :color=' text | userTypeTypeFilter'> {{ text | userTypeFilter }} </a-tag>
      </span>
      <span slot='description' slot-scope='text'>
        <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
      </span>

      <span slot='action' slot-scope='text, record'>
        <template>
          <a @click='handleEdit(record)'>编辑</a>
          <a-divider type='vertical' />
          <a class='del-link' @click='showDeleteConfirm(record)'>删除</a>
        </template>
      </span>
    </s-table>

    <create-form
      ref='createModal'
      :visible='visible'
      :loading='confirmLoading'
      :model='mdl'
      @role-selected='(value)=> roleIds = value'
      @cancel='handleCancel'
      @ok='handleOk'
    />

    <!--    <assign-->
    <!--      ref='assignModal'-->
    <!--      :visible='assignVisable'-->
    <!--      :loading='assignLoading'-->
    <!--      @cancel='handleAssignCancel'-->
    <!--      @ok='handleAssignOk'-->
    <!--    />-->
  </business-layout>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import notification from 'ant-design-vue/es/notification'
import { resetPassword } from '@/api/login'
import { findUserByPage, addUser, deleteUserById, updateUser, assignUserRoles, findUserById } from '@/api/user'

import CreateForm from './CreateForm'
import Assign from './assign.vue'

const columns = [
  {
    title: '序号',
    dataIndex: 'serial',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '账号',
    dataIndex: 'username'
  },
  {
    title: '用户名',
    dataIndex: 'nickName'
  },
  {
    title: '电话',
    dataIndex: 'phone'
  },
  {
    title: '用户类型',
    dataIndex: 'userType',
    scopedSlots: { customRender: 'userType' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '200px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'WorkOrder',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    Assign
  },
  data() {
    this.columns = columns
    return {
      form: this.$form.createForm(this),
      // create model
      visible: false,
      assignVisable: false,
      assignLoading: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return findUserByPage(requestParameters)
          .then(res => {
            return res
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      roleIds: []
    }
  },
  filters: {
    statusFilter(value) {
      return value ? '已启用' : '已禁用'
    },
    statusTypeFilter(value) {
      return value ? 'green' : 'red'
    },
    userTypeFilter(value) {
      return +value === 1 ? '管理员' : '普通用户'
    },
    userTypeTypeFilter(value) {
      return +value === 1 ? 'red' : 'blue'
    }
  },
  created() {
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.info
    })
  },
  mounted() {
    console.log(this.$refs.table)
  },
  beforeDestroy() { // 订阅事件记得要取消
  },
  methods: {
    handleAssign() {
      this.assignVisable = true
    },
    handleAssignOk() {
      // this.assignVisable = false
    },
    // handleAssignCancel() {
    //   this.assignVisable = false
    // },
    handleResetData() {
      this.queryParam = {}
      this.form.resetFields()
      this.$refs.table.refresh()
    },
    handleQueryData(e) {
      e.preventDefault()
      const form = this.form
      const that = this
      const queryObj = {}
      form.validateFields((error, values) => {
        Object.keys(values).forEach(key => {
          if (values[key]) {
            queryObj[key] = values[key]
          }
        })
        this.queryParam = queryObj
        that.$refs.table.refresh()
      })
    },
    handleAdd() {
      this.mdl = null
      this.$refs.createModal.imageUrl = null
      this.visible = true
    },
    async handleEdit(record) {
      const { id } = record
      const result = await findUserById({ userId: id })
      if (result) {
        this.visible = true
        this.mdl = { ...result, password: '******' }
      }
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields(async (errors, values) => {
        if (!errors) {
          const password = values.password
          if (values.id) {
            try {
              delete values.password
              const upres = await updateUser(values)
              // 是否修改了密码
              if (password !== '******') {
                // 调用修改密码接口
                resetPassword({
                  username: values.user,
                  password: password,
                  phone: values.phone,
                  rePassword: password
                }).then(()=>{
                  console.log('密码修改成功!')
                })
              }
              if (upres) {
                let result = null
                if (this.roleIds && this.roleIds.length) {
                  result = await assignUserRoles({
                    roleIds: this.roleIds,
                    userId: upres.id
                  })
                } else {
                  this.visible = false
                }
                if (result) {
                  this.visible = false
                  this.confirmLoading = false
                  // 重置表单数据
                  form.resetFields()
                  this.$message.success('更新成功')
                  // 刷新表格
                  this.$refs.table.refresh()

                } else {
                  this.$refs.table.refresh()
                  this.$message.success('更新成功')
                  this.confirmLoading = false
                }
              } else {
                this.confirmLoading = false
              }
            } finally {
              this.confirmLoading = false
            }
          } else {
            try {
              const addres = await addUser(values)
              // 新增
              if (addres) {
                let result = null
                if (this.roleIds && this.roleIds.length) {
                  result = await assignUserRoles({
                    roleIds: this.roleIds,
                    userId: addres.id
                  })
                } else {
                  this.visible = false
                }
                if (result) {
                  this.visible = false
                  this.confirmLoading = false
                  // 重置表单数据
                  form.resetFields()
                  // 刷新表格
                  this.$refs.table.refresh()
                  this.$message.success('新增成功')
                } else {
                  this.$refs.table.refresh()
                  this.$message.success('新增成功')
                  this.confirmLoading = false
                }
              } else {
                this.confirmLoading = false
              }
            } finally {
              this.confirmLoading = false
            }
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    showDeleteConfirm(record) {
      console.log(record)
      const that = this
      console.log(this.userInfo)
      const currentUserName = this.userInfo.username
      this.$confirm({
        title: '提示?',
        content: '当前操作不可逆、是否继续？',
        okType: 'danger',
        async onOk() {
          const result = await deleteUserById({ userId: record.id })
          if (result) {
            that.$message.success(`${record.username} 删除成功`)
            if (currentUserName == record.username) {
              notification.error({
                message: '错误',
                description: '当前账号已过期、请重新登录!'
              })
              setTimeout(() => {
                that.$store.dispatch('Logout').then(() => {
                  window.location.reload()
                })
              }, 800)
            }
            that.$refs.table.refresh()
          }
        },
        onCancel() {
          console.log('Cancel')
        }
      })
    },
    handleSub(record) {
      this.$confirm({
        title: '提示?',
        content: '确定要锁定所选用户么？',
        onOk() {
          this.$message.success(`${record.no} 锁定成功`)
        },
        onCancel() {
          console.log('Cancel')
        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
